package com.luonan.interceptors;



import com.luonan.utils.JwtUtil;
import com.luonan.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//创建一个拦截器，只需要实现了HandlerInterceptor(处理拦截前)的类就是一个拦截器
//创建后add到WebMVC配置中才生效
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到前端的token
        String token = request.getHeader("Authorization");
        ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
        String RedisToken=stringStringValueOperations.get(token);
        //验证
        try {

            if (RedisToken == null || !RedisToken.equals(token)) {
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);//验证后获取map
            ThreadLocalUtil.set(claims);//存入线程安全中

            return true;
        } catch (Exception e) {
//            出现异常说明token有错，不让放行
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
